<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="upload"
  >
    <img v-if="value" :src="value" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon" />

    <!-- 进度条 -->
    <el-progress v-if="showProgress" :percentage="percent" />
  </el-upload>
</template>

<script>
import { Progress } from "element-ui";

// 下面的代码是固定写法
const COS = require("cos-js-sdk-v5");
// 填写自己腾讯云中的key  id 密钥
const cos = new COS({
  SecretId: "AKIDnSt65pKaaMxKTN5aqwnTv86qLbbLo1zi",
  SecretKey: "Xpqb9TWLuEDwPcZG8l8FsFPJxKRVVRDm"
});

export default {
    props:{
        value:{
            type:String,
            default:''
            // required:true
        }
    },
  data() {
    return {
      showProgress: false,
      imageUrl: "",
      percent: 0
    };
  },
  methods: {
    upload(res) {
      console.log("图片", res);
      //   res.file 文件对象
      //  1.将文件对象上传到腾讯云
      if (res.file) {
        this.showProgress=true
        cos.putObject(
          {
            Bucket: "wh81-1257017897" /* 存储桶 */,
            Region: "ap-nanjing" /* 存储桶所在地域，必须字段 */,
            Key: res.file.name /* 文件名 */,
            StorageClass: "STANDARD", // 上传模式, 标准模式
            Body: res.file, // 上传文件对象
            // 监控文件上传的速度：进度条
            onProgress: ProgressData => {
              this.percent = ProgressData.percent * 100;
            }
          },(err, data) => {
            // 无论上传成功还是失败，都会执行该回调函数，如果成功，那么就打印data
            console.log(err || data);
            this.showProgress=false
            // 上传成功之后
            if (data.statusCode === 200) {
              // console.log('this.imageUrl',this.imageUrl);
              this.$emit('input',`https:${data.Location}`)
            }
          }
        );
        //  2.接收腾讯云返回的图片地址，保存自己的项目中
      }
    },
    beforeAvatarUpload(file) {
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isPNG) {
        this.$message.error("上传头像图片只能是 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isPNG && isLt2M;
    }
  }
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>